import React, { Component } from 'react';
import { Button, Row, Col, Divider } from 'antd';
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';
import PropTypes from 'prop-types';

export default class ImageCrop extends Component {
	constructor(props) {
		super(props);
		this.cropper = null;
		this.imgRef = React.createRef();
	}
	componentDidMount() {
		this.cropper = new Cropper(this.imgRef.current, {
			viewMode: 1,
			zoomable: false,
			restore: true,
			preview: '#preview'
		});
	}
	onSubmit() {
		this.cropper.getCroppedCanvas().toBlob((blob) => {
			const reader = new FileReader();
			reader.readAsDataURL(blob);
			reader.onloadend = (e) => {
				this.setState({
					visible: false
				});
				this.props.onNextStep(reader.result);
			};
		});
	}
	render() {
		return (
			<div>
				<Row gutter={16}>
					<Col sm={24} md={16}>
						<div>
							<img ref={this.imgRef} src={this.props.imageData} style={{ width: '100%', maxHeight: '300px' }} />
						</div>
					</Col>
					<Col sm={24} md={8} ref="reviewBox">
						<h4>图片预览</h4>
						<Row
							id="preview"
							style={{
								width: '100%',
								height: '300px',
								overflow: 'hidden'
							}}
						/>
					</Col>
				</Row>
				<Divider />
				<Row type="flex" justify="end">
					<Button type="primary" onClick={this.onSubmit.bind(this)}>
						下一步
					</Button>
				</Row>
			</div>
		);
	}
}

ImageCrop.propTypes = {
	imageData: PropTypes.string.isRequired,
	onNextStep: PropTypes.func.isRequired
};
